import { useBoolean, useRequest, useSet, useSetState } from 'ahooks';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import style from './style.module.scss';
import { Input, Button, Notify, Tag, Popup } from 'react-vant'
import OSS from 'ali-oss';
import { emojiList, reaplceEmojiToString, replaceStringToEmoji } from '../../emoji';
import { useParams, useSearchParams } from 'react-router-dom';
import { getChathistoryList, sendMessage } from '../../api';



interface DoctorState {
  recordId: number //	问诊id
  doctorId: number //	医生id
  imagePic: string	// 	医生形象照
  doctorName: string //	string	医生姓名
  department: string	// string	科室
  jobTitle: string	 // string	职称
  evaluateStatus: number //	评价状态
  userName: string	// string	医生极光IM账户
  jiGuangPwd: string	 //string	医生极光密码
  inquiryTime: string  // long	问诊时间
}

interface HistoryListState {
  askTime: number
  content: string | { type: string, url: string }
  direction: number
  doctorHeadPic: string
  msgType: number
  userHeadPic: string
}
const ws = new WebSocket('ws://localhost:7000')

const Index: React.FC = () => {
  const [searamParams] = useSearchParams()
  const user_nickname = searamParams.get('user_nickname')
  const param = useParams()
  const userId = param.userId as string
  const recordId = param.recordId as string
  // 滚动元素
  const scrollEl = useRef<HTMLDivElement | null>(null)
  // 发送消息 的请求参数
  const [params, setParams] = useSetState({
    inquiryId: recordId,
    // 原来字符串
    content: '',
    type: 1,
    userId: userId
  })
  // 转换表情之后的内容
  const content = useMemo(() => {
    return replaceStringToEmoji(params.content)
  }, [params.content])
  // 发送消息函数
  const send = async (param = params, isClear = true) => {
    const resp = await sendMessage(param);
    if (resp.data.status === '0000') {
      if (isClear) {
        setParams({
          content: ''
        })
      }
      ws.send(JSON.stringify({ type: 'updateChatHistory' }))
    }
  }

  // 请求历史记录参数
  const [historyParam, setHistoryParam] = useSetState({
    recordId: recordId,
    count: 20,
    page: 1
  })
  // 聊天记录
  const [historyList, setHistoryList] = useState<HistoryListState[]>([])
  // 请求函数历史记录参数
  const getHistoryList = async () => {
    const resp = await getChathistoryList(historyParam);
    setHistoryList(resp.data.result.reverse().map(v => {
      try {
        const data = JSON.parse(v.content);
        if (typeof data === 'number') return v
        if (Array.isArray(data)) return v
        v.content = data
        return v
      } catch {
        return v
      }
    }))
  }

  useEffect(() => {
    // 服务器向客户端推送
    ws.addEventListener('message', ({ data }) => {
      const result = JSON.parse(data);
      if (result.type === 'getChatHistory') {
        getHistoryList()
      }
    })
  }, [])

  useEffect(() => {
    getHistoryList()
  }, [historyParam])

  useEffect(() => {
    if (scrollEl.current)
      scrollEl.current.scrollTop = 10000000
  }, [historyList])
  /********************************** 发送媒体 ******************************************/
  const inputRef = useRef<HTMLInputElement | null>(null)
  const hnadleClickInput = () => inputRef.current?.click();
  const uploadImage = async () => {
    const input = inputRef.current as HTMLInputElement;
    const files = input.files as FileList
    const file = files[0] as File
    if (!file.type.includes('image') && !file.type.includes('video')) {
      Notify.show({ type: 'danger', message: '只允许发送的媒体是图片或者视频' })
      return;
    }
    if (file.size > 1024 * 1024 * 50) {
      Notify.show({ type: 'danger', message: '媒体最大不可以超过50MB' })
      return;
    }
    const type = file.type.includes('image') ? 'image' : 'video'
    // 发送 oss
    // 1. 创建 oss 实例
    const client = new OSS({
      region: 'oss-cn-shanghai',
      accessKeyId: 'LTAI5tEF6SXY58gNaKQsZcxD',
      accessKeySecret: 'KUwe276Rg8uWGUWyoIDLlaSjzCJZLH',
      bucket: 'wd-lt',
    })
    // 2. 上传 媒体
    const resp = await client.put(file.name, file)
    // 3. 媒体路径
    const data = { type: type, url: resp.url };
    const content = JSON.stringify(data);
    send({ ...params, content: content }, false)
  }
  /********************************** 发送表情 ******************************************/
  const [showEmoji, { setTrue, setFalse }] = useBoolean(false);
  const addEmojiToContent = (v: { rule: string, content: string }) => {
    setFalse();
    setParams({
      content: params.content + v.rule
    })
  }
  return (
    <div>

      <input type="file" style={{ display: 'none' }} ref={inputRef} onChange={uploadImage} />
      <div style={{ height: 50, borderBottom: '1px solid #ccc' }}>
        <h3 style={{ textAlign: 'center', lineHeight: "51px", height: 51 }}>{user_nickname}</h3>
      </div>
      <div className={style.chat_list} ref={scrollEl}>
        {
          historyList.map((item, index) => {
            const listClassName = item.direction === 1 ? style.right : style.left
            const avatarUrl = item.direction === 1 ? item.doctorHeadPic : item.userHeadPic
            return (
              <div key={index}>
                {
                  <div className={listClassName}>
                    <img src={avatarUrl} alt="" className={style.avator} />
                    <div className={style.content}>
                      {typeof item.content === 'string'
                        ? <span>{replaceStringToEmoji(item.content)}</span>
                        : (item.content.type === 'image' ? <img className={style.list_image} src={item.content.url} alt="" /> : <video className={style.list_image} controls src={item.content.url}></video>)
                      }
                    </div>

                  </div>
                }
                {/* {
                  item.direction === 2 && <div className={style.left}>
                    <img src={item.doctorHeadPic} alt="" className={style.avator} />
                    <div className={style.content}>
                      {typeof item.content === 'string'
                        ? <span>{item.content}</span>
                        : (item.content.type === 'image' ? <img className={style.list_image} src={item.content.url} alt="" /> : <video controls src={item.content.url}></video>)
                      }
                    </div>
                  </div>
                } */}
              </div>
            )
          })
        }

      </div>
      <div className={style.btm}>
        <Input placeholder='请发送消息' className={style.input} value={content} onChange={value => setParams({ content: reaplceEmojiToString(value) })} onKeyDown={e => e.keyCode === 13 && send()}></Input>
        <div className={style.emjio} onClick={() => setTrue()}>😊</div>
        <Button type="primary" className={style.btn} onClick={() => hnadleClickInput()}>+</Button>
      </div>

      <Popup visible={showEmoji} onClose={() => setFalse()} position="bottom">
        <div style={{ padding: '10px 10px' }}>
          <h3>请选择表情：</h3>
          <div className={style.emoji_list}>
            {
              emojiList.map((v, i) => {
                return <span key={i} className={style.emoji_item} onClick={() => addEmojiToContent(v)}>{v.content}</span>
              })
            }
          </div>
        </div>

      </Popup>
    </div>
  )
}

export default Index

{/* <div className={style.left}>
<img src="https://wx2.sinaimg.cn/mw690/af6f43e2gy1hnhapc3t4xj218w0u0dmb.jpg" alt="" className={style.avator} />
<div className={style.content}>
  放弃哦哪里玩当前难为情去晚了；名单去晚了噩梦的期望去我去
  放弃哦哪里玩当前难为情去晚了；名单去晚了噩梦的期望去我去 放弃哦哪里玩当前难为情去晚了；名单去晚了噩梦的期望去我去
</div>
</div>
<div className={style.right}>
<img src="https://wx2.sinaimg.cn/mw690/af6f43e2gy1hnhapc3t4xj218w0u0dmb.jpg" alt="" className={style.avator} />
<div className={style.content}>
  放弃哦哪里玩当前难为情去晚了；名单去晚了噩梦的期望去我去 放弃哦哪里玩当前难为情去晚了；名单去晚了噩梦的期望去我去 放弃哦哪里玩当前难为情去晚了；名单去晚了噩梦的期望去我去 放弃哦哪里玩当前难为情去晚了；名单去晚了噩梦的期望去我去
</div>
</div>
<div className={style.time}>上午 11:20</div> */}